from openai import OpenAI
import sys
from sys_util import *

config_file = 'config.ini'
client = OpenAI(api_key=read_config_value(config_file, 'Credentials', 'API_KEY'))

model = read_config_value(config_file, 'ChatParameters', 'model')
temperature = float(read_config_value(config_file, 'ChatParameters', 'temperature'))
max_tokens = int(read_config_value(config_file, 'ChatParameters', 'max_tokens'))

def generate_answer(messages,
                    model=model,
                    temperature=temperature,
                    max_tokens=max_tokens):
    completion = client.chat.completions.create(
        model=model,
        messages=messages,
        temperature=temperature,
        max_tokens=max_tokens,
    )
    new_message_content = completion.choices[0].message.content
    print(new_message_content)
    return new_message_content

def generate_answer_stream(messages,
                    model=model,
                    temperature=temperature,
                    max_tokens=max_tokens):
    completion = client.chat.completions.create(
        model=model,
        messages=messages,
        temperature=temperature,
        max_tokens=max_tokens,
        stream=True,
    )
    new_message_content = ""
    for chunk in completion:
        chunk_message = chunk.choices[0].delta.content
        # print(chunk_message or "", end="")
        sys.stdout.write(chunk_message or "")
        sys.stdout.flush()
        new_message_content += (chunk_message or "")
    print()
    return new_message_content